<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\PCHController;


/**
 * App\Models\User
 *
 * @property int $id
 * @property string $user_name 用户名
 * @property string $user_coin 用户余额
 * @property string $user_password 用户密码
 * @property string $user_salt 盐值
 * @property string $user_sign 签名
 * @property string $user_reg_time 注册时间
 * @property string $user_last_login_time 上次登录时间
 * @property string $user_birthday 生日
 * @property string $user_sex 性别 1男 2女
 * @property string $user_nickname 昵称
 * @property string $user_avatar 头像
 * @property string $user_token 令牌
 * @property string $union_id union_id
 * @property string $open_id open_id
 * @property string $is_push is_push
 * @property string $user_score 积分
 * @property string $defaultAddress 默认地址
 * @property string $is_first 是否首次充值 1首冲  0不是
 * @property string $Invite_code 邀请码
 * @property int $BNF_Lv1 上级  邀请受益人
 * @property int $BNF_Lv2 次级  邀请受益人
 * @property int $BNF_Lv3 三级  邀请受益人
 * @property int $BNF_Lv4 四级  邀请受益人
 * @property string $login_type 登录类型  WxLogin TxLogin mobile
 * @property int $is_disabled 是否禁用用户
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereBNFLv1($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereBNFLv2($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereBNFLv3($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereBNFLv4($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereDefaultAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereInviteCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereIsDisabled($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereIsFirst($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereIsPush($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereLoginType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereOpenId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUnionId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserAvatar($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserBirthday($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserCoin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserLastLoginTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserNickname($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserPassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserRegTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserSalt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserScore($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserSex($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserSign($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereUserToken($value)
 * @mixin \Eloquent
 * @property int|null $is_vip
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereIsVip($value)
 */
class User extends Model
{
    public $table       = 'user';
    public $timestamps  = false;
    protected $guarded = [];
    public static $error='';
    public static function getUserList($key,$val)
    {
        if (!empty($key)&&!empty($val)){
            $data = self::where($key,'like','%'.$val.'%')->get();
        }else{
            $data = self::all();
        }

        if (!empty($data)){
            $data = $data->toArray();
        }else{
            $data = [];
        }
        return $data;
    }


    public static function unBindVip($uid)
    {
        $flag = self::where('id','=',$uid)->update(['is_vip'=>0]);
        self::getUserInfoById($uid);
        return $flag;
    }

    /**
     * @param $uid
     * @return mixed
     * 获取用户信息
     */
    public static function getUserInfoById($uid)
    {
        $key    = PCHController::getUserInfoKeyByUID($uid);
        $user   = Redis::HGETALL($key);
        if (!empty($user)){
            return $user;
        }

        $user = self::find($uid);
        if ($user){
            $user = $user->toArray();

            if (isset($user['user_password'])){
                $user['isset_pass'] = true;
                unset($user['user_password']);
            }else{
                $user['isset_pass'] = false;
            }
            unset($user['user_token']);
            unset($user['user_salt']);
            Redis::HMSET($key,$user);
        }else{
            $user = [];
        }
        return $user;
    }

    /**被邀请的人的已经注册的用户id
     * 邀请码
     * @param $user_id     int  被邀请人id
     * @param $invite_code int  邀请人邀请码
     */
    public function invitaion_red_bag($user_id,$invite_code)
    {
        //邀请人model
        $user_model = self::query()->where('invite_code','=',$invite_code)->first();

        if (empty($user_model)){
            return false;
        }else{
            $user_model = $user_model->toArray();
        }
        //查出该用户的上三级用户
        $distribution = [
            'BNF_Lv1' => $user_model['id'],
            'BNF_Lv2' => $user_model['BNF_Lv1'],
            'BNF_Lv3' => $user_model['BNF_Lv2'],
//            'BNF_Lv4' => $user_model['BNF_Lv3'],
        ];
        //插入被邀请人的上四级用户
        $res4 = self::query()->where('id',$user_id)->update($distribution);
        //获取红包金额限制
        $total_coount = SystemConfig::getConfValByConfKey('red_bag_total_amount')['conf_val'];

        $total_coount = $total_coount?:0;

        //给被邀请人和邀请人红包
        $total_coount = round($total_coount,2);
        $res_1 = self::where('id',$user_id)->increment('withdraw',$total_coount); //被邀请人加红包
        $res_2 = self::query()->where('id',$user_model['id'])->increment( 'withdraw',$total_coount);//邀请人加红包
        Balance::addRecord([
            'uid'     => $user_id,
            'amount'  => $total_coount,
            'title'   => '获取红包',
            'type'    => 2,
            'origin'  => 1,
        ]);
        Balance::addRecord([
            'uid'     => $user_model['id'],
            'amount'  => $total_coount,
            'title'   => '获取红包',
            'type'    => 2,
            'origin'  => 1,
        ]);
        if(!$res_1){
            self::$error = '被邀请人获取红包失败';
            return false;
        }

        if(!$res_2){
            self::$error = '邀请人获得红包失败';
            return false;
        }
        $data  = [
            'higher_uid'   => $distribution['BNF_Lv1'],
            'lower_uid'    => $user_id,
            'total_amount' => $total_coount,
            'created_at'   => Carbon::now()
        ];
        $flag = RedBag::insertGetId($data);
        return $flag;
    }

    /**通用的获取任意分销层级的用户列表的函数
     * @param $user_id    int  要获取的用户id
     * @param array $level mixed  该用户的所属层级
     * @return array
     */
    public function get_invite_user_list($user_id,$level=[])
    {
        if(!is_array($level) && !is_numeric($level)){
            return [];
        }
        $level = is_numeric($level) ? [$level] : $level;
        $query = self::query();
        foreach($level as $val){
            $query -> orWhere('BNF_Lv'.$val,'=',$user_id);
        }
        return $query ->select('user_name AS phone','user_nickname AS nickname','user_reg_time AS reg_time') -> get() -> toArray();
    }

    /**检测是否绑定过open_id
     * @param $uid
     * @return bool
     */
    public function is_bind_openId($uid)
    {
        if(!$user_model = self::find($uid)){
            return true;
        }

        return empty($user_model->open_id) ? false : true;

    }

    public static function getUserInfoByOpenId($open_id)
    {
        $userModel = self::query()
            -> where("open_id",'=',$open_id)
            -> first();
        if(empty($userModel)){
            return false;
        }

        return $userModel->toArray();
    }

    public static function getUserDistribution($uid)
    {
        $User = self::where('id',$uid)->first();
        if (empty($data)){
            return false;
        }
        $User = $data->toArray();
        $BNF_LV = [
            'BNF_Lv1' => $User['BNF_Lv1'],
            'BNF_Lv2' => $User['BNF_Lv2'],
            'BNF_Lv3' => $User['BNF_Lv3'],
        ];
        $BNF_user = self::whereIn('id',$BNF_LV)->get();
        if (empty($BNF_user)){

        }
    }


}
